package bs.jizhang.controller;

import bs.jizhang.model.Cashflows;
import bs.jizhang.repository.CashflowRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/cashflow")
public class CashflowController {

    @Autowired
    private CashflowRepository cashflowRepository;

    @GetMapping("/test-error")
    public Map<String, Object> testError() {
        // 故意抛出异常
        throw new RuntimeException("这是一个测试异常");
    }

    // 获取账单列表（支持分页和排序）
    @GetMapping("/list")
    public Map<String, Object> list(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id,asc") String sort) {
        Map<String, Object> response = new HashMap<>();
        Map<String, Object> data = new HashMap<>();

        // 解析排序参数
        String[] sortParams = sort.split(",");
        Sort.Direction direction = Sort.Direction.fromString(sortParams[1]);
        Sort sortBy = Sort.by(direction, sortParams[0]);

        // 创建分页对象
        Pageable pageable = PageRequest.of(page, size, sortBy);

        // 查询分页数据
        Page<Cashflows> res = cashflowRepository.findAll(pageable);

        // 构建响应
        data.put("list", res.getContent());
        data.put("totalElements", res.getTotalElements());
        data.put("totalPages", res.getTotalPages());
        data.put("currentPage", res.getNumber());
        data.put("pageSize", res.getSize());
        data.put("hasNextPage", res.hasNext());

        response.put("code", 0);
        response.put("data", data);

        return response;
    }

    // 获取账单详情
    @GetMapping("/get/{id}")
    public Map<String, Object> get(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        Cashflows data = cashflowRepository.findById(id).orElse(null);
        if (data != null) {
            response.put("status", 0);
            response.put("msg", "Cashflow details retrieved successfully");
            response.put("data", data);
        } else {
            response.put("status", 1);
            response.put("msg", "Cashflow not found");
        }
        return response;
    }

    // 添加账单
    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody Cashflows cashflow) {
        Map<String, Object> response = new HashMap<>();
        Cashflows savedCashflow = cashflowRepository.save(cashflow);
        response.put("status", 0);
        response.put("msg", "Cashflow added successfully");
        response.put("data", savedCashflow);
        return response;
    }

    // 修改账单
    @PutMapping("/update/{id}")
    public Map<String, Object> update(@PathVariable Long id, @RequestBody Cashflows cashflow) {
        Map<String, Object> response = new HashMap<>();
        if (cashflowRepository.existsById(id)) {
            cashflow.setId(id);
            Cashflows updatedCashflow = cashflowRepository.save(cashflow);
            response.put("status", 0);
            response.put("msg", "Cashflow updated successfully");
            response.put("data", updatedCashflow);
        } else {
            response.put("status", 1);
            response.put("msg", "Cashflow not found");
        }
        return response;
    }

    // 删除账单
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        if (cashflowRepository.existsById(id)) {
            cashflowRepository.deleteById(id);
            response.put("status", 0);
            response.put("msg", "Cashflow deleted successfully");
        } else {
            response.put("status", 1);
            response.put("msg", "Cashflow not found");
        }
        return response;
    }
}